package com.huluobo.apps.view

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.apps.AppsIntent
import com.huluobo.apps.AppsViewModel
import com.huluobo.apps.entity.AppsEntity
import com.huluobo.apps.entity.AppsEntityItem
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.HttpType
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

/**
 *  Created by LC on 2025/3/26.
 */
@Composable
fun AppsPage(navHostController: NavHostController, vm: AppsViewModel = hiltViewModel()) {
    val list = remember {
        //快照状态的list,可以根据页面的变化来改变,也是Compose形式常用的list类型
        SnapshotStateList<AppsEntityItem>()
    }

    //弹出下载进度条
    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //弹出安装的进度条
    var launch by remember {
        mutableStateOf(false)
    }

    //进度条的当前进度
    var currentProgress by remember {
        mutableStateOf(0f)
    }

    //控制更新进度的协程
    var scope = rememberCoroutineScope()


    //Compose中的协程作用域
    LaunchedEffect(key1 = "", block = {
        //接受数据的状态
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        Log.e("TagA", "获取应用程序列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        if (it.type == HttpType.DEFAULT) {
                            list.addAll(it.data as AppsEntity)
                        }

                        if (it.type == HttpType.DOWNLOAD) {
                            isShowProgress = false
                            ToastUtils.showLong("下载成功")
                        }
                    }
                }
            }
        }

        //发起请求的意图
        vm.sendIntent(AppsIntent.GetApps)
    })

    Column(Modifier.padding(10.dp)) {
        Box(contentAlignment = Alignment.CenterStart, modifier = Modifier.padding(10.dp)) {
            Text(text = "在线引用", textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth())
            Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "", modifier = Modifier.clickable {
                navHostController.popBackStack()
            })
        }

        LazyVerticalGrid(columns = GridCells.Fixed(3), content = {
            items(list) {
                AppsItem(appsEntityItem = it, vm, onClick = {
                    isShowProgress = true
                }, longClick = {
                    launch = true
                    scope.launch {
                        for (i in 1..100) {
                            currentProgress = i.toFloat() / 100
                            delay(100)
                        }
                        launch = false
                        ToastUtils.showLong("安装成功")
                    }
                })
            }
        }, horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp))

        if (isShowProgress) {
            CircularProgressIndicator()
        }

        if (launch) {
            LinearProgressIndicator(
                progress = currentProgress,
                Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 40.dp)
            )
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AppsItem(appsEntityItem: AppsEntityItem, vm: AppsViewModel, onClick: () -> Unit, longClick: () -> Unit) {
    var isShow by remember {
        mutableStateOf(false)
    }

    //获取当前app的下载文件夹,如果没有就会自动创建一个
    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.combinedClickable(
        onClick = {
            isShow = true
        },
        onLongClick = {
            longClick()
        }
    )) {
        AsyncImage(model = appsEntityItem.appIcon, contentDescription = "", modifier = Modifier.size(40.dp))
        Text(text = appsEntityItem.appName)
    }

    if (isShow) {
        AlertDialog(onDismissRequest = { isShow = false }, confirmButton = {
            TextButton(onClick = {
                vm.sendIntent(
                    AppsIntent.DownloadApk(
                        appsEntityItem.apkUrl,
                        File(file, appsEntityItem.appName + ".apk")
                    )
                )
                onClick()
                isShow = false
            }) {
                Text(text = "确认")
            }
        }, dismissButton = {
            TextButton(onClick = {
                isShow = false
            }) {
                Text(text = "取消")
            }
        }, title = {
            Text(text = "下载提醒")
        }, text = {
            Text(text = "是否要下载${appsEntityItem.appName}吗?")
        })
    }
}